package cn.kgc.http;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;

public class HttpServerHandler extends SimpleChannelInboundHandler<HttpObject> {

    /**
     * 从channel中读取数据
     */
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, HttpObject httpObject) throws Exception {
        if (httpObject != null) {
            //如果是一个http请求
            Channel channel = channelHandlerContext.channel();

            //将返回的响应信息保存到缓存中
            ByteBuf byteBuf = Unpooled.copiedBuffer("hello world".getBytes());

            System.out.println("客户端的Ip地址是：" + channel.remoteAddress());
            //封装发送给客户端的响应信息
            HttpResponse response = new DefaultFullHttpResponse(
                    HttpVersion.HTTP_1_1,
                    HttpResponseStatus.OK,
                    byteBuf
            );
            //设置响应头信息（返回的数据格式）
            response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain;charset=UTF-8");
            //设置响应头信息（返回的数据长度）
            response.headers().set(HttpHeaderNames.CONTENT_LENGTH, byteBuf.readableBytes());

            //将响应信息写入到缓存中channel  将响应信息发送给客户端
            channelHandlerContext.writeAndFlush(response);
        }
    }
}
